import chooseImg from './chooseImg.js'

const onPaste = (e) => {
  if (!(e.clipboardData && e.clipboardData.items)) {
    return
  }
  // 去除html格式
  let pastedText
  if (window.clipboardData && window.clipboardData.getData) {
    // 获取拷贝进剪切板指定格式的数据 (此处用的Text格式)
    pastedText = window.clipboardData.getData('Text')
  } else if ((e.clipboardData || e.originalEvent.clipboardData) && (e.clipboardData || e.originalEvent.clipboardData).getData) {
    pastedText = (e.originalEvent || e).clipboardData.getData('text/plain')
  }
  return new Promise((resolve) => {
    const list = []
    Object.keys(e.clipboardData.items).forEach(key => {
      list.push(e.clipboardData.items[key])
    })
    if (pastedText) {
      resolve({ content: pastedText, oneImg: true })
      return
    }
    const imgEle = list.find(item => item.type == 'image/png')
    if (imgEle) {
      const pasteFile = imgEle.getAsFile()
      const imgEvent = {
        target: {
          files: [pasteFile]
        }
      }
      return chooseImg(imgEvent, (res) => {
        resolve({ content: res.url, file: pasteFile, width: res.width, height: res.height })
      })
    }
    const textEle = list.find(item => item.type == 'text/plain')
    if (textEle) {
      return textEle.getAsString((str) => {
        console.info({ text: str })
        resolve({ content: str })
      })
    }
  })
}

export default onPaste
